import React, { Component } from "react";
import { Affix, Button, Form, message } from "antd";
import { messages } from "share/common";
import { formDecorator } from "./decorator";
import Priority from "components/template/priority/priority";
import "styles/request-and-expense-settings/invoice-check-form.scss";
import {
  invoiceCheckPostServiceMap,
  invoiceCheckPriorityServiceMap,
} from "containers/supplier-management/invoice-management/dataSources";

@Form.create()
@formDecorator
class InvoiceCheckForm extends Component {
  state = {
    formList: {},
    submitLoading: false,
  };

  componentWillMount() {
    const { tab } = this.props;
    this.handleInitPriority();
    this.setState({ formList: this.handleLevelMessage(tab).formList });
  }

  handleInitPriority() {
    let { priority = {} } = this.state;
    const {
      params: {
        tenant,
        companyNameList,
        companies,
        levelCode,
        levelOrgId,
        levelOrgName,
      },
    } = this.props;
    if (!levelOrgId) {
      this.setState({
        priority: {
          levelCode: "TENANT",
          levelOrgId: tenant.id,
          levelOrgName: tenant.tenantName,
        },
      });
      return;
    }
    priority.distribution = {};
    companies &&
      (priority.distribution.companies = companies.map((item, index) => {
        return {
          name: companyNameList[index],
          id: item + "",
        };
      }));
    priority = { ...priority, levelCode, levelOrgId, levelOrgName };
    this.setState({ priority });
  }

  componentDidMount() {
    let {
      tab,
      params: {
        priority,
        duplicatedReceipt,
        consecutiveReceipt,
        invalidTitleReceipt,
        cancelledReceipt,
        trueTestCode,
        goodsServiceName,
        salesParty,
        canGenerateInvoice,
        expenseTypeLimit,
        invoiceLabel,
        businessType,
        reimbursementType,
        enableTax,
        defaultTaxRate,
        receiptToInvoiceOptId,
        allReceiptTaxed,
        separationInvoiceOptId,
      },
      form: { setFieldsValue },
    } = this.props;
    if (tab === "invoice-to-cost" && receiptToInvoiceOptId) {
      setTimeout(() => {
        setFieldsValue({
          priority,
          duplicatedReceipt,
          consecutiveReceipt,
          invalidTitleReceipt,
          cancelledReceipt,
          trueTestCode,
          goodsServiceName,
          salesParty,
          canGenerateInvoice,
          expenseTypeLimit,
        });
      });
      return;
    }
    if (tab === "price-tax" && separationInvoiceOptId) {
      const obj = {
        invoiceLabel,
        businessType,
        reimbursementType,
        defaultTaxRate,
      };
      Object.keys(obj).map((item) => {
        obj[item] && (obj[item] = [obj[item]]);
      });
      setTimeout(() => {
        setFieldsValue({
          priority,
          allReceiptTaxed,
          enableTax,
          ...obj,
          expenseTypeLimit2: expenseTypeLimit,
        });
      });
      return;
    }

    ["price-tax", "invoice-to-cost"].includes(tab) &&
      this.handleInitPriorityValue();
  }

  handleInitPriorityValue = async () => {
    const {
      tab,
      form: { setFieldsValue },
    } = this.props;
    const ret = await invoiceCheckPriorityServiceMap.get(tab)();
    setFieldsValue({ priority: ret.data + 1 });
  };

  handlePriority = (priority) => {
    this.setState({ priority });
  };

  handleCancel = () => {
    this.props.close();
  };

  handleSave = () => {
    const {
      form: { validateFieldsAndScroll },
      params,
      tab,
    } = this.props;
    const {
      priority,
      priority: { distribution },
    } = this.state;
    if (
      priority &&
      priority.levelCode === "TENANT" &&
      priority.distribution &&
      priority.distribution.companies &&
      priority.distribution.companies.length === 0
    ) {
      message.error(messages("expense-3.key174") /*请选择启用公司*/);
      return;
    }
    validateFieldsAndScroll(async (errors, values) => {
      if (!errors) {
        if (
          tab === "price-tax" &&
          values.expenseTypeLimit2 &&
          values.expenseTypeLimit2.length > 50
        ) {
          message.error(
            messages("expense-3.key175") /*单条规则最多只能选择50条费用类型*/
          );
          return;
        }
        this.setState({ submitLoading: true });
        distribution &&
          distribution.companies &&
          (priority.companies = distribution.companies.map((item) => item.id));
        delete priority.distribution;
        delete params.companies;
        delete params.tenant;
        delete params.tab;
        if (tab === "price-tax") {
          Object.keys(values).map((item) => {
            if (
              ![
                "enableTax",
                "allReceiptTaxed",
                "priority",
                "expenseTypeLimit2",
              ].includes(item)
            ) {
              values[item] && (values[item] = values[item][0]);
            }
          });
          values.expenseTypeLimit = values.expenseTypeLimit2;
          delete values.expenseTypeLimit2;
        }
        try {
          await invoiceCheckPostServiceMap.get(tab)({
            ...params,
            ...values,
            ...priority,
          });
          message.success(
            messages("common.save.success", { arg1: "" }) /*{arg1} 保存成功*/
          );
          this.props.close(true);
        } catch (e) {}
        this.setState({ submitLoading: false });
      }
    });
  };

  render() {
    const {
      params: { readOnly },
    } = this.props;
    const { priority, submitLoading } = this.state;
    const formArray = this.renderFormList();
    formArray.splice(
      1,
      0,
      <Priority
        top="TENANT"
        single={false}
        required
        onChange={this.handlePriority}
        disabled={readOnly}
        disabledTop
        companyProps={{ disabled: readOnly }}
        defaultValue={priority}
        formItemLayout={{}}
      />
    );
    return (
      <section className="invoice-check-form">
        <Form className="new-form">
          {formArray}
          <Affix offsetBottom={0} className="slide-footer">
            <Button
              type="primary"
              loading={submitLoading}
              disabled={readOnly}
              htmlType="submit"
              onClick={this.handleSave}
            >
              {messages("common.save") /*保存*/}
            </Button>
            <Button
              loading={submitLoading}
              onClick={this.handleCancel}
              disabled={readOnly}
            >
              {messages("common.cancel") /*取消*/}
            </Button>
          </Affix>
        </Form>
      </section>
    );
  }
}

InvoiceCheckForm.propTypes = {};

export default InvoiceCheckForm;
